# -*- encoding:utf-8 -*-
# @Time: 2022/11/12 0:56
# @Author: qiujixian
# @Email: 1253598817@qq.com
# @File: serializers.py
# @Software: PyCharm

from rest_framework import serializers
from .models import Student, Classes

# class StudentSerializer(serializers.Serializer):
    # #label='ID' 表示前端该字段名显示为ID,备注名
    # #read_only=True 表示只读
    # id = serializers.CharField(label='ID', read_only=True)
    # name = serializers.CharField(max_length=30, label='姓名')
    # #required=False 表示用户可以不传值，可以为空
    # age = serializers.IntegerField(label='年龄', required=False)
    # sex = serializers.IntegerField(label='性别', required=False)
    # create_time = serializers.DateTimeField(label='创建时间', required=False)
    # update_time = serializers.DateTimeField(label='更新时间', required=False)
    # is_delete = serializers.BooleanField(label='逻辑删除', default=False, required=False)
    #
    # def create(self, validated_data):
    #     # 数据的创建
    #     return Student.objects.create(**validated_data)   # {'name':'qiujixian','age':18}
    #
    # def update(self, instance, validated_data):
    #     # 数据的修改
    #     instance.name = validated_data.get('name', instance.name)
    #     instance.age = validated_data.get('age', instance.age)
    #     instance.sex = validated_data.get('sex', instance.sex)
    #     instance.save()
    #     return instance
class StudentSerializer(serializers.ModelSerializer):
    # 重写 默认展示classes=classes.id，重写后展示classes=classes.__str__()
    # classes = serializers.StringRelatedField(label='班级')
    # 增加一个字段, source返回模型对象的字段
    class_name = serializers.CharField(source='classes.name', read_only=True)

    class Meta:
        model = Student
        # fields = '__all__'  # 指定映射的字段，__all__ 表示所有的字段
        exclude = ['is_delete']   # 除了is_delete字段，其他都显示（映射）
        #逻辑校验过滤，下面表示age最小的值为0，最大的值为200
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 200}
        }

    # def validate_name(self, value):
    #     # 追加额外的逻辑校验，属性级别的，对单个字段进行校验
    #     if 'mq' not in value.lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     return value

    # def validate(self, data):
    #     # 追加额外的逻辑校验-对象级别的，会把传入的所有数据都传入date  date = {'name': '皮卡邱', 'age': 18}
    #     if 'mq' not in data['name'].lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     elif data['age'] < 18:
    #         raise serializers.ValidationError('未成年禁止访问')
    #     return data

class StudentSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'name', 'age', 'sex']

class ClassesSerializer(serializers.ModelSerializer):
    # 嵌套序列化，对管理器进行操作
    student_set = StudentSerializerSimple(many=True, read_only=True)

    class Meta:
        model = Classes
        # fields = '__all__'
        exclude = ['is_delete']










